/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.workflow.price;

import com.bifrost.entity.Customer;
import com.bifrost.entity.Order;
import com.bifrost.exception.PricingException;
import com.bifrost.repository.CouponDetailRepository;
import com.bifrost.repository.CustomerRepository;
import com.bifrost.service.CouponService;
import com.bifrost.workflow.BaseActivity;
import com.bifrost.workflow.ProcessContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigInteger;

/**
 * 积分抵消
 *
 * @author joewee
 * @version 1.0.0
 * @Date 2017/11/14 13:55
 */
@Component("bonusPointsActivity")
public class BonusPointsActivity extends BaseActivity<ProcessContext<Order>> {
    @Autowired
    CouponService couponService;
    @Autowired
    CouponDetailRepository couponDetailRepository;
    @Autowired
    CustomerRepository customerRepository;
    public static final int ORDER = 5500;

    public BonusPointsActivity() {
        setOrder(ORDER);
    }

    @Override
    public ProcessContext<Order> execute(ProcessContext<Order> context) throws Exception {
        Order order = context.getSeedData();
        if (Boolean.TRUE.equals(order.isBonusPointsUsed())) {
            Customer customer = order.getCustomer();
            BigInteger bonus = customer.getBonusPoints();
            BigInteger bonusUsed = order.getBonusPointsUsed();
            if (bonus == null) {
                bonus = BigInteger.ZERO;
            }
            if (bonusUsed == null || bonusUsed.compareTo(BigInteger.ZERO) <= 0) {
                bonusUsed = BigInteger.ZERO;
            }
            //使用积分大于所有积分
            if (bonus.compareTo(bonusUsed) < 0) {
                throw new PricingException(String.format("用户：%d：%s积分余额不足：%d，使用%d", customer.getCustomerId(), customer.getCustomerLastname(), bonus, bonusUsed));
            }
            order.setBonusPointsUsed(bonusUsed);
        } else {
            order.setBonusPointsUsed(BigInteger.ZERO);
            order.setIsBonusPointsUsed(Boolean.FALSE);
        }
        return context;
    }
}
